package com.wanlian.upload.modules.app.controller;

import com.wanlian.File.FileUtils;
import com.wanlian.json.JsonResult;
import com.wanlian.util.ImageUtils;
import com.wanlian.util.Utils;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/file")
@EnableAutoConfiguration
public class FileController {

    private HttpServletRequest request;

    @Value(value = "${file.saveDir}")
    private String dpath;//"D:\\holl7\\test\\IOS测试图\\IOS测试图";
    @Value(value = "${file.urlRooPath}")
    private String urlRooPath;

    @RequestMapping(value = "/upload")
    @ResponseBody
    public String upload(@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request,
                         HttpServletResponse response) {
        this.request = request;
        setAccessDomain(response);
        try {
            String path = "/file/dir";
            String fileName = Utils.getFilename(file.getOriginalFilename());
            String srcFilePath = String.format("%s/%s", dpath, fileName);
            File targetFile = new File(srcFilePath);
            String dstFileName = Utils.getFilename(file.getOriginalFilename());
            String dstFilePath = String.format("%s/%s", dpath, dstFileName);
            System.out.println(srcFilePath);
            System.out.println(dstFileName);
            file.transferTo(targetFile);
            ImageUtils.compressImage(srcFilePath, dstFilePath);
            String urlPath = String.format("%s/%s/%s", urlRooPath, path, dstFileName);
            return new JsonResult().SerailzeUrl(urlPath);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult().Serailze(false, "上传文件失败！");
        }
    }

    @RequestMapping(value = "/upload/nosrc")
    @ResponseBody
    public String uploadNotSaveSrc(@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request,
                                   HttpServletResponse response) {
        this.request = request;
        setAccessDomain(response);
        try {
            String path = "file/dir";
            String fileName = Utils.getFilename(file.getOriginalFilename());
            boolean check = checkCanCompress(fileName);
            if (check) {
                String srcFilePath = String.format("%s/%s", dpath, fileName);
                File targetFile = new File(srcFilePath);
                String dstFileName = Utils.getFilename(file.getOriginalFilename());
                String dstFilePath = String.format("%s/%s", dpath, dstFileName);
                System.out.println(srcFilePath);
                System.out.println(dstFileName);
                file.transferTo(targetFile);
                ImageUtils.compressByZIP(srcFilePath, dstFilePath);
                String urlPath = String.format("%s/%s/%s", urlRooPath, path, dstFileName);
                FileUtils.deleteFile(srcFilePath);
                return new JsonResult().SerailzeUrl(urlPath);
            } else {
                return new JsonResult().Serailze(false, "文件不能压缩");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult().Serailze(false, "上传文件失败！");
        }
    }

    private boolean checkCanCompress(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (suffix.equals("gif")) {
            return true;
        } else if (suffix.equals("bmp")) {
            return true;
        } else if (suffix.equals("jpg")) {
            return true;
        } else if (suffix.equals("png")) {
            return true;
        } else if (suffix.equals("jpeg")) {
            return true;
        } else {
            return false;
        }
    }

    private void setAccessDomain(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
    }

    @RequestMapping(value = "/upload/files")
    public String upload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        setAccessDomain(response);
        try {
            String path = "/upload";
            List<String> Lists = new ArrayList<String>();
            for (MultipartFile multipartFile : files) {
                String fileName = Utils.getFilename(multipartFile.getOriginalFilename());
                File targetFile = new File(dpath, fileName);
                System.out.println(dpath + "/" + fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                multipartFile.transferTo(targetFile);
                String urlpath = String.format("%s%s/%s", urlRooPath, path, fileName);
                Lists.add(urlpath);
            }
            return new JsonResult().Serailze(Lists);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult().Serailze(false, "上传文件失败！");
        }
    }

    @RequestMapping(value = "/dir/{path}", method = {RequestMethod.GET})
    public void publicImg(@PathVariable("path") String path, HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setContentType("image/jpeg");// 设置响应类型，告知浏览器输出的是图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Set-Cookie", "name=value; HttpOnly");// 设置HttpOnly属性,防止Xss攻击
        response.setDateHeader("Expire", 0);
        try {
            String filePath = dpath + "/" + path;
            byte[] data = getLocalPicture(filePath);
            Integer contentLength = data.length;
            response.setHeader("content-length", contentLength + "");
            response.getOutputStream().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static byte[] getLocalPicture(String path) throws Exception {
        byte[] data = null;
        FileImageInputStream input = new FileImageInputStream(new File(path));
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int numBytesRead = 0;
        while ((numBytesRead = input.read(buf)) != -1) {
            output.write(buf, 0, numBytesRead);
        }
        data = output.toByteArray();
        output.close();
        input.close();
        return data;
    }

    private static byte[] readInByteArray(File imgFile) {
        try {
            return IOUtils.toByteArray(new FileInputStream(imgFile));

        } catch (IOException e) {
            throw new IllegalStateException("读取待压缩图片过程中出错，请及时联系管理员！", e);

        }
    }

    /*public static void main(String[] args) {
        String dpath="/Users/zhaoxiaotong/Downloads/aaa.jpg";
        String dpath1="/Users/zhaoxiaotong/Downloads/bbb.jpg";
        File targetFile = new File(dpath);
        try {
            byte[] data = ImgTools.compressUnderSize(readInByteArray(targetFile), 150 * 470);
            FileUtils.createNewFile(dpath1, data, true);
         }catch (Exception e){
            System.out.println(e);
        }
    }*/

}
